using UnityEngine;

namespace HyuFrameWork
{
    [RequireComponent(typeof(AudioSource))]
    public class AudioController : MonoBehaviour 
    {
        public AudioHub Hub;
        public void Init(AudioHub hub) 
        {
            Hub = hub;
        }

        public string HubName => Hub == null ? string.Empty : Hub.gameObject.name;

        AudioSource _src;
        public AudioSource Source => _src ??= gameObject.GetOrAddComponent<AudioSource>();
        
        public AudioClip Clip 
        {
            get => Source.clip;
            set => Source.clip = value;
        }

        public float Volumn 
        {
            get => Source.volume;
            set => Source.volume = value;
        }

        public bool Mute
        {
            get => Source.mute;
            set => Source.mute = value;
        }
        
        public bool Loop 
        {
            get => Source.loop; 
            set => Source.loop = value;
        }

        // 当前是否正在播放
        public bool IsPlaying => Source.isPlaying;

        // 当前播放的声音总长度秒数
        public float ClipLength => Clip != null ? Clip.length : 0f;
        
        // 当前播放进度秒数
        public float ClipTime 
        {
            get => IsPlaying ? Source.time : 0f; 
            set => Source.time = Mathf.Clamp(value, 0f, ClipLength);
        }
        
        // 播放进度(0f-1f)
        public float ClipProgress 
        {
            get => (ClipLength > 0.0001f) ? (ClipTime / ClipLength) : 0f;
            set => Source.time = Mathf.Clamp01(value) * ClipLength; 
        }

        public void PlayBattleClip(string clipName, bool loop = false,bool cache = true)
            =>PlayClip(Hub.ResService.LoadBattleAudio(clipName,cache),loop);
        
        public void PlayClip(string abName,string clipName, bool loop = false,bool cache = true)
            =>PlayClip(Hub.ResService.LoadAudio(abName,clipName,cache),loop);

        public void PlayClip(AudioClip clip, bool loop = false) => AudioHelper.PlayInstant(Source, clip, loop);

        public void Pause(bool bPause) 
        {
            if (bPause) 
                Source.Pause();
            else 
                Source.UnPause();
        }
        
        public void Stop() 
        {
            Source.Stop();
//            Source.clip = null;
        }
    }
}